<?PHP
//配送分支控制器
class Admin_sendfen_Controller extends controller_admin{
	function __construct(){
		parent::__construct();
	 	$this->assign('nav','配送批次分支');
		$this->assign('menuid1','5'); 
		$this->assign('menuid2','0');
	}
	
	# 配送分支列表
	public function list__(){ 
		if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
		{ 	 
			
			#得到传递过来的参数
			$_POST=format::addslash_deep($_POST);
			if(!isset($_POST['start']))					$_POST['start']			= 0;
			if(!isset($_POST['limit']))					$_POST['limit']			= 10;
			if(!isset($_POST['sort']))			 		$_POST['sort']			= 'a.id';
			if(!isset($_POST['dir']))				 		$_POST['dir']				= 'DESC';
			
			
  	  #查询条件
			$sql_where = ' where  a.sendpi_id="'.$_POST['sendpi_id'].'" ';  
			#排序信息
			$sql_order = " ORDER BY ".$_POST['sort'].' '.$_POST['dir']." LIMIT ".$_POST['start'].", ".$_POST['limit'];
			#先查总数 
			$sql = "
			select 
			count(a.id) 
			from `t_sendfen`  a
			".$sql_where ;  
			$db = factory::getDBO();
			$rows = $db->LoadResult($sql); 
			if($rows){
				#检索出具体数据
				$sql = "select 
					a.*
				from `t_sendfen` a  
				".$sql_where.$sql_order;
				$rs = $db->LoadAssocList($sql);
				#输出结果
				echo '({"total":"'.$rows.'","results":'.json_encode($rs).'})';
			}else{
				echo '({"total":"0","results":[]})';
			}
			exit();  	
			
			
		}
		exit();
	}
 

	
	# 添加 配送分支
	public function add__(){
		//权限判断
		factory::module('admin')->authSys('plan'); 
		if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
		{
			
			$form = format::addslash_json(json_decode( stripslashes($_POST['form']) ));
			$rsfix = format::addslash_json(json_decode( stripslashes($_POST['rsfix']) ));
			$rsslt = format::addslash_json(json_decode( stripslashes($_POST['rsslt']) ));
			$rsuser = format::addslash_json(json_decode( stripslashes($_POST['rsuser']) )); 
			 
			//debug::show($rsuser,$form); 
 			$sendvege = array();
			$packet = ''; 
			$db = factory::getDBO(); 
			$db->begin();
			if($db->loadresult('select count(*) from t_sendfen where sendpi_id="'.$form['sendpi_id'].'" and name="'.$form['name'].'" ') > 0 ){
				exit('操作失败！,当前配送批次中已经存在此【配送分支标识】！');
			}
			$rs_sendpi = $db->loadassoc('select * from t_sendpi where id="'.$form['sendpi_id'].'"');
			if($rs_sendpi['status'] != '0'){
				exit('操作失败！只允许向【计划中】的配送批次添加配送分支！');
			}
			//1 配送分支主表
			$sendfen_id = $db->insert('sendfen',array(
				'sendpi_id'=>$form['sendpi_id'],
				'name'=>$form['name'],
				'users'=>count($rsuser),
				'sltnum'=>$form['sltnum'],
				'packetnum'=>1 ,
				'created_user_id'=>factory::module('admin')->getuserid(),
				'created'=>'now()', 
				'updated_user_id'=>factory::module('admin')->getuserid(),
				'updated'=>'now()'
			));
			if(!$sendfen_id){
				$db->rollback();
				exit('系统繁忙，请稍后重试！');
			} 
			//组装所有配送蔬菜，以及配送标识
			foreach($rsfix as $v){
				$sendvege[] = array(
					'sendpi_id'=>$form['sendpi_id'],
					'sendfen_id'=>$sendfen_id,
					'vege_id'=>$v['vege_id'],
					'vege_num'=>$v['vege_num'],
					'fixed'=>'1'
				);
			}
			foreach($rsslt as $v){
				$sendvege[] = array(
					'sendpi_id'=>$form['sendpi_id'],
					'sendfen_id'=>$sendfen_id,
					'vege_id'=>$v['vege_id'],
					'vege_num'=>$v['vege_num'],
					'fixed'=>'0'
				);
			}
			$packet = factory::module('packet')->encode($sendvege);
			
			//2 配送计划默认的蔬菜 
			$db->insertlist('sendfen_vege',$sendvege);
			
		  //3配送会员
			foreach($rsuser as $v){
				$send_id = $db->insert('send',array(
					'sendpi_id'=>$form['sendpi_id'],
					'sendfen_id'=>$sendfen_id,
					'user_id'=>$v,
					'packet'=>$packet,
					'remark'=>'',
					'created_user_id'=>factory::module('admin')->getuserid(),
					'created'=>'now()', 
					'updated_user_id'=>factory::module('admin')->getuserid(),
					'updated'=>'now()'
				));
				foreach($sendvege as $val){
					$db->insert('send_vege',array(
						'sendpi_id'=>$form['sendpi_id'],
						'sendfen_id'=>$sendfen_id,
						'send_id'=>$send_id,
						'vege_id'=>$val['vege_id'],
						'vege_num'=>$val['vege_num'],
						'fixed'=>$val['fixed'],
					));
				}
			}			
			#更新配送批次的包装种类信息等等
			if(!factory::module('sendpi')->updateit($form['sendpi_id'])){
				exit('操作失败！');
			}
			if($rs_sendpi['onsource'] == '1'){
				#更新溯源信息
				if(!factory::module('source')->update($rs_sendpi['id'])){
					$db->rollback();
					exit('系统繁忙，请稍后重试！');
				}
				$rs_source = $db->loadassoc('select * from t_source where sendpi_id="'.$rs_sendpi['id'].'" ');
				# 写日志
				factory::module('source')->logs($rs_source['id'],factory::module('admin')->getuserid(),'配送批次增加配送分支，进行溯源更新');
			}
			
			$db->commit();
			exit('{success:1,msg:"添加成功！"}');
			 
			exit();
		}
		$_GET=format::addslash_deep($_GET);
		$sendpi_id = intval($_GET['sendpi_id']);
		if(isset($_GET['sendfen_id'])){
			$sendfen_id = intval($_GET['sendfen_id']);
		}else{
			$sendfen_id = '0';
		}
		
		
		$db = factory::getDBO();
	  # 配送批次信息
		$rs_sendpi = $db->loadassoc('select a.*,b.username as created_username,c.username as updated_username from `t_sendpi` a left join t_user b on a.created_user_id=b.id left join t_user c on a.updated_user_id=c.id  where a.deleted=0 and a.id="'.$sendpi_id.'" ');
		if(!$rs_sendpi){
			exit('没有查到任何记录！');
		}
		if($rs_sendpi['status'] != '0'){
			exit('操作失败！只允许向【计划中】的配送批次增加配送分支！');
		}
		$this->assign('rs_sendpi',$rs_sendpi);
		
		
		# 是否有默认的蔬菜
		$fix_veges = array();
		$slt_veges = array();
		if($sendfen_id != '0'){
			$rs_sendfen = $db->loadassoc('select * from t_sendfen where id="'.$sendfen_id.'" ');
			if($rs_sendfen)
			{
				/*   id=123
  name=香菜 */
				$fix_veges = $db->loadassoclist('select a.vege_id as id,b.name from t_sendfen_vege a left join t_vege b on a.vege_id=b.id where a.sendfen_id="'.$sendfen_id.'" and a.fixed=1 ');
				$slt_veges = $db->loadassoclist('select a.vege_id as id,b.name from t_sendfen_vege a left join t_vege b on a.vege_id=b.id where a.sendfen_id="'.$sendfen_id.'" and a.fixed=0 ');
				
			}
		}
		$fix_veges = array('vege_ids'=>$fix_veges);
		$slt_veges = array('vege_ids'=>$slt_veges);
	 //debug::show($sendfen_id,$fix_veges,$slt_veges);
		
		$this->assign('fix_veges',$fix_veges);
		$this->assign('slt_veges',$slt_veges);
		# 蔬菜
		$this->assign('rs_veges',$db->loadassoclist('select * from `t_vege` where deleted=0 ','id'));
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 删除配送分支
	 */
	public function del__(){
		//权限判断
		factory::module('admin')->authSys('plan'); 
		if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
		{
			$id = $_POST['id']; 
			$db = factory::getDBO();
			$rs = $db->loadassoc('select a.*,b.status,b.onsource from t_sendfen a left join t_sendpi b on a.sendpi_id=b.id where a.id="'.$id.'"');
			if(!$rs) exit('没有查到任何记录，请重新操作！'); 
			if($rs['status'] != '0'){
				exit('操作失败！当前所属配送批次状态必须为【计划中】！');
			}
			$db = factory::getDBO(); 
			$db->begin();
			if(!$db->query('delete from t_sendfen where id="'.$id.'" ')){
				exit('系统繁忙，请稍后再试！');
			}
			if(!$db->query('delete from t_sendfen_vege where sendfen_id="'.$id.'" ')){
				exit('系统繁忙，请稍后再试！');
			}
			if(!$db->query('delete from t_send where sendfen_id="'.$id.'" ')){
				exit('系统繁忙，请稍后再试！');
			}
			if(!$db->query('delete from t_send_vege where sendfen_id="'.$id.'" ')){
				exit('系统繁忙，请稍后再试！');
			}
			#更新配送批次的包装种类信息等等
			if(!factory::module('sendpi')->updateit($rs['sendpi_id'])){
				exit('操作失败！');
			}
			
			
			
			if($rs['onsource'] == '1'){
				#更新溯源信息
				if(!factory::module('source')->update($rs['sendpi_id'])){
					$db->rollback();
					exit('系统繁忙，请稍后重试！');
				}
				$rs_source = $db->loadassoc('select * from t_source where sendpi_id="'.$rs['sendpi_id'].'" ');
				# 写日志
				factory::module('source')->logs($rs_source['id'],factory::module('admin')->getuserid(),'配送批次删除配送分支，进行溯源更新');
			}			
			

			
			
			
			$db->commit(); 
			exit('{success:1,msg:"操作成功！"}');
		}	
		exit();
	}
	 
	/* 批次修改 */
	public function modify__(){ 
		//权限判断
		factory::module('admin')->authSys('plan'); 
		$_GET=format::addslash_deep($_GET);
		$sendfen_id = intval($_GET['id']);
		$db = factory::getDBO();
		
	  # 配送批次信息
		$rs_sendfen = $db->loadassoc('select a.*,d.status,b.username as created_username,c.username as updated_username from `t_sendfen` a left join t_user b on a.created_user_id=b.id left join t_user c on a.updated_user_id=c.id left join t_sendpi d on a.sendpi_id=d.id  where  a.id="'.$sendfen_id.'" ');
		if(!$rs_sendfen){
			url::msgBox('没有查到任何记录！','-1');
		}
		if($rs_sendfen['status'] != '0'){
			exit('操作失败！当前所属配送批次状态必须为【计划中】！');
		} 
		$this->assign('rs_sendfen',$rs_sendfen);
		
		
		
		# 配送信息
		$rs_sendfen_vege = $db->loadassoclist('select a.*,b.code,b.name from `t_sendfen_vege` a left join t_vege b on a.vege_id=b.id  where a.sendfen_id="'.$sendfen_id.'" ');
		$this->assign('rs_sendfen_vege',$rs_sendfen_vege);
		

		# 包装个数
		$rs_packet = $db->loadassoclist('select distinct(packet) from t_send where sendfen_id="'.$sendfen_id.'" ');
		
		$packetindex = array();
		foreach($rs_packet as $k=>&$v){
			$v['veges'] = factory::module('packet')->decode($v['packet']);
			$v['veges_string'] = factory::module('packet')->decode($v['packet'],'string');
			$v['veges_html'] = factory::module('packet')->decode($v['packet'],'html');
			$v['usernum'] = $db->loadresult('select count(*) from t_send where sendfen_id="'.$sendfen_id.'" and packet="'.$v['packet'].'" ');
			$packetindex[$v['packet']] = ($k+1);
		}
		
		
		$this->assign('rs_packet',$rs_packet);
		
		# 包装序列
		$this->assign('packetindex',$packetindex);
	}
	 
	/* 配送批次中的会员列表 */
	public function pi_modify_userlist__(){
		if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
		{
			#得到传递过来的参数
			$_POST=format::addslash_deep($_POST);
			if(!isset($_POST['start']))					$_POST['start']			= 0;
			if(!isset($_POST['limit']))					$_POST['limit']			= 10;
			if(!isset($_POST['sort']))			 		$_POST['sort']			= 'a.id';
			if(!isset($_POST['dir']))				 		$_POST['dir']				= 'DESC';
			if(!isset($_POST['keywords']))   		$_POST['keywords']  = ''; 
			if(!isset($_POST['packettype']))    $_POST['packettype']  = ''; 
			
  	  #查询条件
			$sql_where = ' where  a.sendfen_id="'.$_POST['sendfen_id'].'" '.func::speedsearch($_POST['keywords'],array( 'a.remark','b.username' 	,'b.name' ));  
			if($_POST['packettype']!=''){
				$sql_where .= ' and a.packet= "'.$_POST['packettype'].'"';	
			}
			#排序信息
			$sql_order = " ORDER BY ".$_POST['sort'].' '.$_POST['dir']." LIMIT ".$_POST['start'].", ".$_POST['limit'];
			#先查总数 
			$sql = "
			select 
			count(a.id) 
			from `t_send` a left join t_user b on a.user_id=b.id  
			left join t_list_user_classes c on b.classes=c.id 
			".$sql_where ;  
			$db = factory::getDBO();
			$rows = $db->LoadResult($sql); 
			if($rows){
				#检索出具体数据
				$sql = "select 
					a.*,
					b.username,
					b.name,
					c.val as classes
				from `t_send` a left join t_user b on a.user_id=b.id 
			left join t_list_user_classes c on b.classes=c.id 
				".$sql_where.$sql_order;
				$rs = $db->LoadAssocList($sql);
				foreach($rs as $k=>&$v){
					$v['veges'] = factory::module('packet')->decode($v['packet']);
					$v['veges_string'] = factory::module('packet')->decode($v['packet'],'string');
					$v['veges_html'] = factory::module('packet')->decode($v['packet'],'html');
				}
				#输出结果
				echo '({"total":"'.$rows.'","results":'.json_encode($rs).'})';
			}else{
				echo '({"total":"0","results":[]})';
			}
			exit();  
		}
	}
	
	
	
	/* 批次编辑中，移除会员 */
	public function pi_modify_removeuser__(){
		//权限判断
		factory::module('admin')->authSys('plan'); 
		if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
		{
			$id = $_POST['id']; 
			$db = factory::getDBO();
			$rs_send = $db->loadassoc('select * from t_send where id="'.$id.'"');
			if(!$rs_send) exit('没有查到任何记录，请重新操作！');
			$rs_sendpi = $db->loadassoc('select * from t_sendpi where id="'.$rs_send['sendpi_id'].'"');
			if(!$rs_sendpi) exit('没有查到任何记录，请重新操作！');
			if($rs_sendpi['status'] != '0'){
				exit('操作失败！只允许删除【计划中】的会员配送！');
			} 
			$db->begin();
			if(!$db->query('delete from t_send where id="'.$rs_send['id'].'" ')){
				exit('系统繁忙，请稍后再试！');
			}
			if(!$db->query('delete from t_send_vege where send_id="'.$rs_send['id'].'" ')){
				exit('系统繁忙，请稍后再试！');
			}
			if(!factory::module('sendfen')->updatefen($rs_send['sendfen_id'])){
				exit('系统繁忙，请稍后再试！');
			}
			
			
			if($rs_sendpi['onsource'] == '1'){
				#更新溯源信息
				if(!factory::module('source')->update($rs_send['sendpi_id'])){
					$db->rollback();
					exit('系统繁忙，请稍后重试！');
				}
				$rs_source = $db->loadassoc('select * from t_source where sendpi_id="'.$rs_send['sendpi_id'].'" ');
				# 写日志
				factory::module('source')->logs($rs_source['id'],factory::module('admin')->getuserid(),'配送分支移除会员配送，进行溯源更新');
			}



			
			
			
			$db->commit(); 
			exit('{success:1,msg:"操作成功！"}');
		}	
		exit();
	}
	/* 批次编辑中，增加会员 */
	public function pi_modify_adduser__(){ 
		//权限判断
		factory::module('admin')->authSys('plan'); 
		if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
		{
			$ids = format::addslash_json(json_decode( stripslashes($_POST['ids']) ));
			$_POST=format::addslash_deep($_POST);
			$sendfen_id = $_POST['sendfen_id'];
			$db = factory::getDBO();
			$db->begin();
			$rs_sendpi = $db->loadassoc('select a.*,b.status,b.onsource from t_sendfen a left join t_sendpi b on a.sendpi_id=b.id where a.id="'.$sendfen_id.'"');
			if(!$rs_sendpi) exit('没有查到任何记录，请重新操作！');		
			if($rs_sendpi['status'] != '0'){
				exit('操作失败！只允许修改【计划中】的会员配送！');
			}
			
			$rs_sendfen_vege = $db->loadassoclist('select * from t_sendfen_vege where sendfen_id="'.$sendfen_id.'" ');
			$packet = factory::module('packet')->encode($rs_sendfen_vege);
			
			$optuser = 0;
			foreach($ids as $v){
				if($db->loadresult('select count(*) from t_send where sendfen_id="'.$sendfen_id.'" and user_id="'.$v['id'].'" ')<=0){
					$optuser++;
					$send_id = $db->insert('send',array(
						'sendpi_id'=>$rs_sendpi['sendpi_id'],
						'sendfen_id'=>$sendfen_id,
						'user_id'=>$v['id'],
						'packet'=>$packet,
						'remark'=>'',
						'created_user_id'=>factory::module('admin')->getuserid(),
						'created'=>'now()', 
						'updated_user_id'=>factory::module('admin')->getuserid(),
						'updated'=>'now()'
					));
					foreach($rs_sendfen_vege as $val){
						$db->insert('send_vege',array(
							'sendpi_id'=>$rs_sendpi['sendpi_id'],
							'sendfen_id'=>$sendfen_id,
							'send_id'=>$send_id,
							'vege_id'=>$val['vege_id'],
							'vege_num'=>$val['vege_num'],
							'fixed'=>$val['fixed']
						));
					}
				}
			}
			if(!factory::module('sendfen')->updatefen($sendfen_id)){
				exit('系统繁忙，请稍后再试！');
			}
			
			
			if($rs_sendpi['onsource'] == '1'){
				#更新溯源信息
				if(!factory::module('source')->update($rs_sendpi['sendpi_id'])){
					$db->rollback();
					exit('系统繁忙，请稍后重试！');
				}
				$rs_source = $db->loadassoc('select * from t_source where sendpi_id="'.$rs_sendpi['sendpi_id'].'" ');
				# 写日志
				factory::module('source')->logs($rs_source['id'],factory::module('admin')->getuserid(),'配送分支增加会员配送，进行溯源更新');
			}			
			
			

			
			
			$db->commit();
			exit('{success:1,msg:"您提交了'.count($ids).'个会员配送！ \r\n\r\n其中'.(count($ids)-$optuser).'个重复，成功新增'.$optuser.'个会员配送！\r\n"}');
		}
		exit('');
	}

 



	/* 批次查看 */
	public function view__(){
		$_GET=format::addslash_deep($_GET);
		$sendfen_id = intval($_GET['id']);
		$db = factory::getDBO();
		
	  # 配送批次信息
		$rs_sendfen = $db->loadassoc('select a.*,d.status,b.username as created_username,c.username as updated_username from `t_sendfen` a left join t_user b on a.created_user_id=b.id left join t_user c on a.updated_user_id=c.id left join t_sendpi d on a.sendpi_id=d.id  where  a.id="'.$sendfen_id.'" ');
		if(!$rs_sendfen){
			url::msgBox('没有查到任何记录！','-1');
		}
		
		 
		$this->assign('rs_sendfen',$rs_sendfen);
		
		
		
		# 配送信息
		$rs_sendfen_vege = $db->loadassoclist('select a.*,b.code,b.name from `t_sendfen_vege` a left join t_vege b on a.vege_id=b.id  where a.sendfen_id="'.$sendfen_id.'" ');
		$this->assign('rs_sendfen_vege',$rs_sendfen_vege);
		

		# 包装个数
		$rs_packet = $db->loadassoclist('select distinct(packet) from t_send where sendfen_id="'.$sendfen_id.'" ');
		
		$packetindex = array();
		foreach($rs_packet as $k=>&$v){
			$v['veges'] = factory::module('packet')->decode($v['packet']);
			$v['veges_string'] = factory::module('packet')->decode($v['packet'],'string');
			$v['veges_html'] = factory::module('packet')->decode($v['packet'],'html');
			$v['usernum'] = $db->loadresult('select count(*) from t_send where sendfen_id="'.$sendfen_id.'" and packet="'.$v['packet'].'" ');
			$packetindex[$v['packet']] = ($k+1);
		}
		
		
		$this->assign('rs_packet',$rs_packet);
		
		# 包装序列
		$this->assign('packetindex',$packetindex);
	}

 
}
?>